package top.icecola.community.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.icecola.community.dao.DiscussPostMapper;
import top.icecola.community.dao.LoginTicketMapper;
import top.icecola.community.dao.UserMapper;
import top.icecola.community.domain.*;
import top.icecola.community.util.CommunityConstant;
import top.icecola.community.util.CommunityUtil;
import top.icecola.community.util.MailClient;

import java.util.*;

@Service
public class UserService implements CommunityConstant {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    public List<User> selectAll(){
        List<User> userList= userMapper.selectByExample(new UserExample());
         return userList;
    }

    public PageResponse userPage(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userMapper.selectByExample(new UserExample());
        return new PageResponse(((Page)users).getTotal(),users);
    }

    public User findUserById(Integer userId) {
       return userMapper.selectByPrimaryKey(userId);
    }
    public User findUserByUsername(String username){
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(userExample);
        if(userList.isEmpty()) {
            return null;
        }else {
            return userList.get(0);
        }

    }
    public User findUserByEmail(String email){
        UserExample userExample = new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        List<User> userList = userMapper.selectByExample(userExample);
        if(userList.isEmpty()){
            return null;
        }else{
            return userList.get(0);
        }
    }

    private void updateStatus(int userId) {
        User user = findUserById(userId);
        user.setStatus(1);
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdEqualTo(userId);
        userMapper.updateByExample(user,userExample);
    }

    private void insertUser(LoginTicket loginTicket){
        loginTicketMapper.insert(loginTicket);
    }

    private LoginTicket selectLoginByTicket(String ticket){
        LoginTicketExample loginTicketExample = new LoginTicketExample();
        loginTicketExample.createCriteria().andTicketEqualTo(ticket);
        List<LoginTicket> loginTickets = loginTicketMapper.selectByExample(loginTicketExample);
        if(loginTickets.isEmpty()){
            return null;
        }else{
            return loginTickets.get(0);
        }
    }

//    更新用户登录状态
    private void updateTicketStatus(String ticket,int status){
        LoginTicket loginTicket = selectLoginByTicket(ticket);
        loginTicket.setStatus(status);
        LoginTicketExample loginTicketExample = new LoginTicketExample();
        loginTicketExample.createCriteria().andTicketEqualTo(ticket);
        loginTicketMapper.updateByExample(loginTicket,loginTicketExample);
    }

//    修改头像
    private void updateHeaderUrl(int userId, String headerUrl) {
        User user = findUserById(userId);
        user.setHeaderUrl(headerUrl);
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdEqualTo(userId);
        userMapper.updateByExample(user,userExample);
    }

    public Map<String,Object> register(User user){
        Map<String,Object> map=new HashMap<>();
        if(user==null){
            throw new IllegalArgumentException("参数不能为空");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空");
            return map;
        }
        User u=findUserByUsername(user.getUsername());
        if(u!=null){
            map.put("usernameMsg","该账号已存在");
            return map;
        }
        u=findUserByEmail(user.getEmail());
        if(u!=null){
            map.put("emailMsg","该邮箱已存在");
            return map;
        }
        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insert(user);
        user=findUserByUsername(user.getUsername());

        //激活邮件
        Context context=new Context();
        context.setVariable("email",user.getEmail());
        String url=domain+contextPath+"/activation/"+user.getId()+"/"+user.getActivationCode();
        context.setVariable("url",url);
        String content=templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);
        return map;
    }


    public int activation(int userId, String code) {
        User user = findUserById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            updateStatus(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        // 验证账号
        User user = findUserByUsername(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }

        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        insertUser(loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    public void logout(String ticket){
        updateTicketStatus(ticket,1);
    }

    public LoginTicket findLoginTicket(String ticket) {
        return selectLoginByTicket(ticket);
    }

    public void updateHeader(int userId, String headerUrl) {
        updateHeaderUrl(userId, headerUrl);
    }

    public User findUserByName(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria().andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(userExample);
        if(userList.isEmpty()){
            return null;
        }else{
            return userList.get(0);
        }
    }

    public  Collection<? extends GrantedAuthority> getAuthorities(int userId){
        User user=findUserById(userId);
        List<GrantedAuthority> list=new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch(user.getType()){
                    case 1:
                        return SECURITY_ADMIN;
                    default:
                        return SECURITY_USER;
                }
            }
        });
        return list;
    }

    public List<DiscussPost> selectUserPost(Integer userId,int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        DiscussPostExample discussPostExample = new DiscussPostExample();
        discussPostExample.createCriteria().andUserIdEqualTo(userId).andStatusNotEqualTo(2);
        return discussPostMapper.selectByExample(discussPostExample);
    }

    public List<User> selectAllUser(int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        UserExample userExample=new UserExample();
        return userMapper.selectByExample(userExample);
    }

    public void setStatus(Integer userId,Integer status){
        User user = this.findUserById(userId);
        user.setStatus(status);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public Integer searchUsernameSize(String username){
        UserExample userExample = new UserExample();
        String like="%"+username+"%";
        userExample.createCriteria().andUsernameLike(like);
        List<User> userList = userMapper.selectByExample(userExample);
        return userList.size();
    }
    public List<User> searchUsername(String username,int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        UserExample userExample = new UserExample();
        String like="%"+username+"%";
        userExample.createCriteria().andUsernameLike(like);
        return userMapper.selectByExample(userExample);
    }
}
